#include <iostream>
#include <boost/lexical_cast.hpp>
#include <utils/XString.h>
#include <config/NovelConfig.h>
#include <utils/XTimer.h>
#include "AnalyseArticle.h"

using namespace std;
using namespace ruleconfiguration;

void AnalyseArticle::analyseNovelInfo()
{
  //匹配小说名称
  AnalyseBase::matchSingleValue("NovelName", m_article.articlename);
  matchSingleValue("NovelAuthor", m_article.author);
  static string tmp;
  matchSingleValue("NovelDegree", tmp);
  RegexInfo* reg = m_rule.getRegex("NovelDegree");
  //匹配是否完本
  if(tmp == reg->FilterPattern)//如果写作进程与过滤的字符一致
  {
    m_article.fullflag = '1';
  }
  //匹配小说类别
  matchSingleValue("LagerSort", m_article.sortname);
  NovelConfig::getInstance()->getSortID(m_article.sortname, m_article.sortid);
  //匹配SmallSort小类别(预留)
  //匹配小说简介
  matchSingleValue("NovelIntro", m_article.intro);
  //匹配NovelKeyword关键字(预留)
  //匹配NovelDegree写作进度(预留)
  //匹配默认封面链接地址,如果为默认地址,则不需要下载
  matchSingleValue("NovelDefaultCoverUrl", tmp);
  if(tmp.length() == 0)
  {
    matchSingleValue("NovelCover", m_article.cover);
    if(!m_article.cover.empty()&&
       m_article.cover.find(m_rule.getRegex("GetSiteUrl")->Pattern) == string::npos)
    {
      m_article.cover = m_rule.getRegex("GetSiteUrl")->Pattern +  m_article.cover ;
    }
  }
  //匹配cookie(预留)
  //匹配目录页地址
  matchSingleValue("NovelInfo_GetNovelPubKey", tmp);
  reg = m_rule.getRegex("PubIndexUrl");
  //目录链接=连接替换匹配出的关键字
  static string pubKey;
  pubKey.assign(reg->Pattern);
  XString::replaceAll(pubKey, "{NovelPubKey}", tmp );
  m_article.contentsLink = pubKey;
  //m_article.articleid = boost::lexical_cast<string>(NovelConfig::getInstance()->getMaxArticleID());
}

void AnalyseArticle::setArticleID(unsigned int id)
{
  m_article.articleid = boost::lexical_cast<string>(id);
}

string& AnalyseArticle::analyseNovelSearchUrl(string& articleName,string& url)
{
  //NovelSearchUrl 站点搜索地址 http://www.la66.com/modules/article/search.php
  //NovelSearchData 搜索提交内容  {SearchKey} 表示搜索提交的内容 searchtype=articlename&searchkey={SearchKey}
  //NovelSearch_GetNovelKey 从搜索结果中获得小说编号    {SearchKey} 表示搜索提交的内容  此获得结果存入{NovelKey}变量
  //class="bookcover"><a href="/txt(\d*)/index.html">
  matchSingleValue("NovelSearchUrl",url);
  string data;
  matchSingleValue("NovelSearchData",data);
  XString::replaceAll(data,"{SearchKey}",articleName);
  url+="?";
  url+=data;
  return url;
}

string& AnalyseArticle::getNovelLink(string& url)
{
  //未处理一个名词查询多个的情况
  string novelKey="";
  //string novelUrl="";
  matchSingleValue("NovelSearch_GetNovelKey",novelKey);
  matchSingleValue("NovelUrl",url);
  XString::replaceAll(url,"{NovelKey}",novelKey);

  return url;
}

